package com.jozen.smart_toilet_system;

import com.jozen.modelbase.netwoek.base.ModuleBaseApplication;
import com.jozen.smart_toilet_system.web_socket.AppResponseDispatcher;
import com.qweather.sdk.view.HeConfig;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;
import com.zhangke.websocket.WebSocketSetting;


public class BaseApplication extends ModuleBaseApplication {

    private static BaseApplication instance;

    private static WebSocketManager webSocketManager;

    public static WebSocketManager getWebSocketManager() {
        return webSocketManager;
    }

    @Override
    public void initSmartToilet() {
        instance = this;
        initWebSocket();
        //初始化和风天气SDK
        HeConfig.init("HE2211021022501342", "d82c25bb9d0c4bd2a2cead28ce342b81");
        //切换至免费订阅
        HeConfig.switchToDevService();
    }

    public static synchronized BaseApplication getInstance() {
        return instance;
    }

    public void initWebSocket() {
        try {
            WebSocketSetting setting = new WebSocketSetting();

            //连接地址，必填
            String baseWs = "ws://127.0.0.1:8082";
//            String baseWs = "ws://183.6.57.187:8082";
            setting.setConnectUrl(baseWs);

            //设置连接超时时间
//        setting.setConnectTimeout(15 * 1000);
            setting.setConnectTimeout(0);

            //设置心跳间隔时间
            setting.setConnectionLostTimeout(60);

            //设置断开后的重连次数，可以设置的很大，不会有什么性能上的影响
            setting.setReconnectFrequency(100000);

//        Map<String, String> header = new HashMap<>();
//        header.put(AppConstant.APP_CLIENT, AppConstant.APP_CLIENT_VAL);
////        //设置Header
//        setting.setHttpHeaders(header);

            //设置消息分发器，接收到数据后先进入该类中处理，处理完再发送到下游
            setting.setResponseProcessDispatcher(new AppResponseDispatcher());
            //接收到数据后是否放入子线程处理，只有设置了 ResponseProcessDispatcher 才有意义
            setting.setProcessDataOnBackground(true);

            //网络状态发生变化后是否重连，
            //需要调用 WebSocketHandler.registerNetworkChangedReceiver(context) 方法注册网络监听广播
            setting.setReconnectWithNetworkChanged(true);

            //通过 init 方法初始化默认的 WebSocketManager 对象
            webSocketManager = WebSocketHandler.init(setting);
            //启动连接
            webSocketManager.start();

            //注意，需要在 AndroidManifest 中配置网络状态获取权限
            //注册网路连接状态变化广播
            WebSocketHandler.registerNetworkChangedReceiver(this);
        } catch (Exception e) {

        }

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        try {
            if (webSocketManager != null) {
                webSocketManager.destroy();
            }
        } catch (Exception e) {

        }
    }
}
